package ar.com.fiuba.ElectronicCircuitAnalyst.infrastructure.db4o.repository;

import ar.com.fiuba.ElectronicCircuitAnalyst.domain.api.Component;
import ar.com.fiuba.ElectronicCircuitAnalyst.domain.api.repository.ComponentRepository;
import ar.com.fiuba.ElectronicCircuitAnalyst.domain.exceptions.CircuitElementNotFoundException;
import ar.com.fiuba.ElectronicCircuitAnalyst.domain.exceptions.ElementNotFoundException;
import ar.com.fiuba.ElectronicCircuitAnalyst.domain.impl.ComponentImpl;

import com.db4o.ObjectSet;

public class ComponentRepositoryImpl extends RepositoryImpl<Component> implements ComponentRepository {

	public ComponentRepositoryImpl() {
		super(Component.class);
	}

	public Component getComponentByName(String name) throws CircuitElementNotFoundException {
		return getComponent(name);
	}

	public void removeComponentByName(String name) throws CircuitElementNotFoundException {
		try {
			remove(getComponent(name));
		} catch (ElementNotFoundException e) {
			throw new CircuitElementNotFoundException("Component with the name \"" + name + "\" was not found.");
		}
	}

	private Component getComponent(String name) throws CircuitElementNotFoundException {
		ObjectSet<Component> result = getDb().queryByExample(ComponentImpl.getEmptyComponent(name));

		if (result.size() == 0) {
			throw new CircuitElementNotFoundException("No component found with the given name: " + name);
		}

		return result.get(0);

	}

}
